const router = require('koa-router')()
const fs = require('fs-extra');
const path = require('path');

router.prefix('/user');

var tokenMap = {};

router.get('/', function (ctx, next) {
    ctx.body = 'this is a users response!'
})


router.get('/loginOut', function (ctx, next) {

    var token = ctx.request.query['token'] || ctx.request.body['token'] || ctx.header['token'] || '';

    var redisMap = require('../auth/redis.json')

    if (redisMap.hasOwnProperty(token)) {
        delete redisMap[token]
    }

    ctx.body = {
        success: true,
        code: 1000,
        message: '登陆成功'
    };
})




router.post('/login', function (ctx, next) {

    const { name, pwd, is_auto } = ctx.request.body;

    var redisMap = require('../auth/redis.json')

    var token = ctx.request.query['token'] || ctx.request.body['token'] || ctx.header['token'] || '';

    //is_auto说明是模拟自动登陆
    if (is_auto && token && ctx.request.body.token_user != null) {
        ctx.body = {
            success: true,
            code: 1000,
            message: '登陆成功',
            data: {
                token: token
            }
        };
        ctx.body.add_info = `您提交的数据是name:${name},pwd:${pwd}`
        return
    }

    var token_new = parseInt(Math.random() * 10000000000000000)

    if (name == 'wmg' && pwd == "123") {

        var userInfo = {
            name: 'wmg',
            phone: '18627726186',
            uuid: "100001"
        }



        redisMap[token_new] = userInfo

        fs.writeFile(path.join(__dirname, '../auth/redis.json'), JSON.stringify(redisMap, null, '\t'), function () { });


        ctx.body = {
            success: true,
            code: 1000,
            message: '登陆成功',
            data: {
                token: token_new
            }
        };
    } else {
        ctx.body = {
            success: false,
            code: 0,
            message: '帐号或密码错误'
        };
    }
    ctx.body.add_info = `您提交的数据是name:${name},pwd:${pwd}`

})

router.get('/list', function (ctx, next) {


    var list = [{
        uuid: '1',
        name: '小王',
        age: 30,
        sex: 0,
        address:'湖北省黄冈市**县**镇**村'
    }, {
        uuid: '2',
        name: '小李',
        age: 30,
        sex: 0,
        address:'湖北省黄冈市**县**镇**村'
    }, {
        uuid: '3',
        name: '小吴',
        age: 30,
        sex: 0,
        address:'湖北省黄冈市**县**镇**村'
    },{
        uuid: '4',
        name: '小王',
        age: 30,
        sex: 0,
        address:'湖北省黄冈市**县**镇**村'
    }, {
        uuid: '5',
        name: '小李',
        age: 30,
        sex: 0,
        address:'湖北省黄冈市**县**镇**村'
    }, {
        uuid: '6',
        name: '小吴',
        age: 30,
        sex: 0,
        address:'湖北省黄冈市**县**镇**村'
    }];


    list=list.concat(list).concat(list).concat(list).concat(list).concat(list).concat(list)

    ctx.body = {
        success: true,
        code: 1000,
        message: '获取成功',
        data: list
    }
})

module.exports = router
